import {BrowserRouter, Navigate, Route, Routes} from 'react-router-dom'
import Login from "./components/start/login"
import Start from "./components/start/start"
import Register from "./components/start/register"
import Main from "./components/main/main"
import Home from "./components/main/content/home"
import NoMatch from "./components/main/content/no-match"
import {Suspense, useCallback, useState} from "react"
import routeMap from "./components/main/route-map"

function lazyLoad(name) {
    const Element = routeMap[name]
    if (!Element) return null
    return (
        <Suspense>
            <Element/>
        </Suspense>
    )
}

function App() {
    let [routes, setRoutes] = useState([])
    const onUpdateMenu = useCallback((menu) => {
        const routes = []

        function loadMenu(items, parentPath) {
            for (const item of items) {
                const path = parentPath ? `${parentPath}/${item.name}` : item.name
                const element = lazyLoad(item.name)
                if (element) {
                    routes.push((
                        <Route
                            key={routes.length}
                            path={path}
                            element={element}
                        />
                    ))
                }
                if (item.children) {
                    loadMenu(item.children, path)
                }
            }
        }

        loadMenu(menu)
        setRoutes(routes)
    }, [])

    return (
        <BrowserRouter>
            <Routes>
                <Route index element={<Navigate replace to="/start/login"/>}/>
                <Route path="start" element={<Start/>}>
                    <Route path="login" element={<Login/>}/>
                    <Route path="register" element={<Register/>}/>
                </Route>
                <Route path="main" element={<Main onUpdateMenu={onUpdateMenu}/>}>
                    <Route path="home" element={<Home/>}/>
                    <Route path="*" element={<NoMatch/>}/>
                    {routes}
                </Route>
            </Routes>
        </BrowserRouter>
    )
}

export default App
